package com.zoe.app.controller;

import com.zoe.app.util.MinioUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * @author zoe.Zhang
 * @date 2022/06/27
 * @description
 */

@RestController
@RequestMapping("/minio")
@RequiredArgsConstructor
public class MinioController {

    private final MinioUtil minioUtil;

    @PostMapping
    @SneakyThrows
    //
    public String upload(MultipartFile multipartFile) {
        String fileName = minioUtil.upload(multipartFile);
        return fileName;
    }

    @DeleteMapping("/")
    public Boolean delete(String fileName) {
        return minioUtil.remove(fileName);
    }

    // http://localhost:8080/minio/?fileName=2022-08/24/%E7%B3%BB%E7%BB%9F%E9%9B%86%E6%88%90%E5%AE%98%E6%96%B9%E7%AC%AC%E4%BA%8C%E7%89%882022%E4%B8%8A%E6%A0%87%E6%B3%A8%E7%89%88.pdf
    // 返回的是文件的预览地址
    @GetMapping("/")
    public String preview(String fileName) {
        return minioUtil.preview(fileName);
    }

    @GetMapping("/download")
    public void download(String fileName) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        minioUtil.download(fileName, response);
    }
}
